var pageNum = 0;
var drawLocked = false;
var docObject;
var wisId = "";
var userid = "";
var userName = "";
var classid = "";
var topic_msg = "";
var topic_stu_to_teacher = "";
var topic_teacher_to_stu = "";
var online_count = 0;
var handerStuid = "";
var handerStuname = "";
var dmsPubKey = "";
var dmsSubKey = "";
var rtmp_publish_url = "";
var rtmp_play_url = "";
var hls_play_url = "";
var lssapp_id = "";
var stream_tea = "";
var lss;
var play_status = 0;
var hand_status = 0;
var selmic = 0;
var selcam = 0;
var downloadUrl = "./setup/youtuSetup.exe";
var cryptkey = "";
var crypttime = 0;
var lang = "";

function GetQueryString(param) {
	var request = {
		QueryString : function(val) {
			var uri = window.location.search;
			var re = new RegExp("" + val + "=([^&?]*)", "ig");
			return ((uri.match(re)) ? (decodeURI(uri.match(re)[0]
					.substr(val.length + 1))) : '');
		}
	};
	return request.QueryString(param);
}

/**
 * 获得课件列表
 * 
 * @param option
 */
function getList(option) {
	if (!classid) {
		alert(lang_msg['notinit'][lang]);
		return;
	}
	$.ajax({
		type : "POST",
		timeout : 8000,
		url : "./remoteinvoke.php",
		dataType : "json",
		data : {
			method : 'getClassDocs',
			classid : classid
		},
		success : function(data) {
			if (data.Flag == 100) {
				if (option.success)
					option.success(data.Info);
			} else {
				if (option.failure)
					option.failure(data.FlagString);
			}
		},
		error : option.failure
	});
}

function genK(option) {
	if (!classid) {
		alert(lang_msg['notinit'][lang]);
		return;
	}
	$.ajax({
		type : "POST",
		timeout : 8000,
		url : "./remoteinvoke.php",
		dataType : "json",
		data : {
			method : 'genK',
			appid : option.appid,
			stream : option.stream
		},
		success : function(data) {
			if (data.Flag == 100) {
				if (option.success)
					option.success(data);
			} else {
				if (option.failure)
					option.failure(data.FlagString);
			}
		},
		error : option.failure
	});
}

function loadGenCapturek(err) {
	if (err != null) {
		alert(err);
	}
	var cap_stream = "stream_" + classid.replace(/-/g,'_');
	genK({
		appid : lssapp_id,
		stream : cap_stream,
		success : function(data) {
			console.log(data);
			cryptkey = data.k;
			crypttime = data.t;
			if(cryptkey && cryptkey.length == 32){
				$("#startcapture").show();
			}
		},
		failure : function(errStr) {
			alert(errStr.responseText);
		}
	});
}

var socket;

function startcapture(){
	if(isSupportWebSocket){
		startHtml5capture();
	}else{
		startFlashcapture();
	}
}

function startFlashcapture(){
	if(!cryptkey || cryptkey.length != 32){
		alert(lang_msg['notinit'][lang]);
		return;
	}
	$("#loading_bg").show();
	var classid_tmp = classid.replace(/-/g,"_");
	$("#mycapture").attr("src","youtucapture-launcher://"+lssapp_id+"/"+userid+"/"+classid_tmp+"/"+cryptkey+"/"+crypttime+"/"+lang);
	//延时3秒建立与服务端连接
	setTimeout(function(){
		openFlashSocket(function(state){
			if(state=='opened'){
				$("#loading_bg").hide();
				$("#startcapture").hide();
			}else{
				setTimeout(function(){
					openFlashSocket(function(state){
						if(state=='opened'){
							$("#loading_bg").hide();
							$("#startcapture").hide();
						}else{
							//下载录屏应用
							$("#loading_bg").hide();
							$("#mycapture").attr("src",downloadUrl);
						}
					});
				},5000);
			}
		});
	},3000);
}

WEB_SOCKET_SWF_LOCATION = "WebSocketMain.swf";
WEB_SOCKET_DEBUG = false;

function openFlashSocket(callbackFlashSocket){
	
	socket = new WebSocket("ws://127.0.0.1:5413");
	socket.onopen = function() {
		if(callbackFlashSocket) {
			callbackFlashSocket('opened');
			callbackFlashSocket = null;
		}
    };
    socket.onclose = function() {
    	if(callbackFlashSocket) {
			callbackFlashSocket('closed');
			callbackFlashSocket = null;
		}
    };
    socket.onmessage = function(e) {
        var msg = e.data;
		if(msg=='quitCapture'){
			$("#startcapture").show();
		}
    };
	
}

function startHtml5capture(){
	if(!cryptkey || cryptkey.length != 32){
		alert(lang_msg['invalidParam'][lang]);
		return;
	}
	$("#loading_bg").show();
	var classid_tmp = classid.replace(/-/g,"_");
	$("#mycapture").attr("src","youtucapture-launcher://"+lssapp_id+"/"+userid+"/"+classid_tmp+"/"+cryptkey+"/"+crypttime+"/"+lang);
	//延时3秒建立与服务端连接
	setTimeout(function(){
		openHtml5Socket(function(state){
			if(state=='opened'){
				$("#loading_bg").hide();
				$("#startcapture").hide();
				socket.subscribe("oper");
			}else{
				setTimeout(function(){
					openHtml5Socket(function(state){
						if(state=='opened'){
							$("#loading_bg").hide();
							$("#startcapture").hide();
							socket.subscribe("oper");
						}else{
							//下载录屏应用
							$("#loading_bg").hide();
							$("#mycapture").attr("src",downloadUrl);
						}
					});
				},3000);
			}
		});
	},3000);
}

function openHtml5Socket(callbackHtml5Socket){
	socket = new sgcws("ws://127.0.0.1:5413");
	socket.on('open', function(event){
		if(callbackHtml5Socket) {
			callbackHtml5Socket('opened');
			callbackHtml5Socket = null;
		}
	});
	socket.on('close', function(event){
		if(callbackHtml5Socket) {
			callbackHtml5Socket('closed');
			callbackHtml5Socket = null;
		}
	});
	socket.on('sgcevent', function(event){
		if (event.channel == "oper") {
			var msg = event.message;
			if(msg=='quitCapture'){
				$("#startcapture").show();
			}
		} 
	});

}

/**
 * 获得mp3课件列表
 * 
 * @param option
 */
function getMp3List(option) {
	if (!classid) {
		alert(lang_msg['notinit'][lang]);
		return;
	}
	$.ajax({
		type : "POST",
		timeout : 8000,
		url : "./remoteinvoke.php",
		dataType : "json",
		data : {
			method : 'getClassMp3s',
			classid : classid
		},
		success : function(data) {
			if (data.Flag == 100) {
				if (option.success)
					option.success(data.Info);
			} else {
				if (option.failure)
					option.failure(data.FlagString);
			}
		},
		error : option.failure
	});
}

/**
 * 初始化加载课堂列表
 * 
 * @param err
 */
function loadDocList(err) {
	if (err != null) {
		alert(err);
	}
	$(".docUploader img").remove();
	$(".docUploader a").show();
	$("#uploadForm").attr("src", "uploadForm.html");
	getList({
		success : function(data) {
			console.log(data.result);
			var list = data.result;
			$("#docList").html("");
			for (var i = 0; i < list.length; i++) {
				var itemHtml = "<div docId='"
						+ list[i]["docid"]
						+ "'><span>"
						+ jQuery('<div />').text(
								decodeURIComponent(list[i].docname)).html()
						+ "</span></div>";
				$("#docList").append(itemHtml);
			}
			if (!!docObject) {
				$("#docList div[docId=" + docObject["id"] + "]").addClass(
						"selectDoc");
				$("#docList div[docId=" + docObject["id"] + "]").siblings()
						.removeClass("selectDoc");
			}
			$("#docList div span").click(function() {
				WIS.ChoseDoc({
					docId : $(this).parent().attr("docId"),
					failure : function(errStr) {
						console.log("ChoseDoc:"+errStr);
					}
				});
			});

		},
		failure : function(errStr) {
			alert(errStr.responseText);
		}
	});
}

/**
 * 初始化加载Mp3列表
 * 
 * @param err
 */
function loadMp3List(err) {
	if (err != null) {
		alert(err);
	}
	getMp3List({
		success : function(data) {
			console.log(data.result);
			var list = data.result;
			$("#mp3List").html("");
			for (var i = 0; i < list.length; i++) {
				var itemHtml = "<div docId='"
						+ list[i]["docid"]
						+ "' fileUrl='"+list[i]["fileUrl"]+"'><span>"
						+ jQuery('<div />').text(
								decodeURIComponent(list[i].docname)).html()
						+ "</span></div>";
				$("#mp3List").append(itemHtml);
			}
			
			$("#mp3List div span").click(function() {
				var docId = $(this).parent().attr("docId");
				var fileUrl = "http://www.ykyueke.com" + $(this).parent().attr("fileUrl");
				ROP.Publish('{"oper":"loadmp3","file":"'+fileUrl+'"}',topic_teacher_to_stu);
				loadMp3Player(fileUrl);
				$("#mp3List div[docId=" + docId + "]").addClass("selectMp3");
				$("#mp3List div[docId=" + docId + "]").siblings().removeClass("selectMp3");
			});

		},
		failure : function(errStr) {
			alert(errStr.responseText);
		}
	});
}

/*
 * 初始化参数
 */
function initParam() {
	wisId = GetQueryString("wisid");
	userid = GetQueryString("userid");
	userName = GetQueryString("name");
	classid = GetQueryString("classid");
	topic_msg = GetQueryString("topic");
	topic_stu_to_teacher = GetQueryString("topic") + "_to_teacher";
	topic_teacher_to_stu = GetQueryString("topic") + "_to_stu";
	lssapp_id = GetQueryString("lssapp_id");
	stream_tea = GetQueryString("stream_tea");
	//stream_stu = GetQueryString("stream_stu");
	lang = GetQueryString("lang");
	var selmic_cookie = getCookie("selmic");
	if(selmic_cookie) selmic = selmic_cookie;
	var selcam_cookie = getCookie("selcam");
	if(selcam_cookie) selcam = selcam_cookie;
	loadGenCapturek();
}

function initUrl(data){
	rtmp_publish_url = data.rtmp_publish_url;
	rtmp_play_url = data.rtmp_play_url;
	hls_play_url = data.hls_play_url;
	dmsPubKey = data.dmsPubKey;
	dmsSubKey = data.dmsSubKey;
}

function u_c_t(c, u) {
	if (!c || !u) {
		window.location.href = "paramerror.html";
		return;
	}
	$.ajax({
		type : "POST",
		timeout : 8000,
		url : "./remoteinvoke.php",
		dataType : "json",
		data : {
			method : 'u_c_t',
			classid : c,
			userid : u
		},
		success : function(data) {
			if (data.Flag == 100) {
				if (data.Info && data.Info.result) {
					initUrl(data);
					initWis();
					initTool();
					loadDocList();
					loadMp3List();
					initDms();
					initLss();
				} else {
					window.location.href = "nopower.html";
					return;
				}
			} else {
				window.location.href = "apierror1.html";
				return;
			}
		},
		error : function(error) {
			window.location.href = "apierror2.html";
			return;
		}
	});
}

function u_c_t_c(c, u) {
	if (!c || !u) {
		window.location.href = "paramerror.html";
		return;
	}
	$.ajax({
		type : "POST",
		timeout : 8000,
		url : "./remoteinvoke.php",
		dataType : "json",
		data : {
			method : 'u_c_t',
			classid : c,
			userid : u
		},
		success : function(data) {
			if (data.Flag == 100) {
				if (data.Info && data.Info.result) {

				} else {
					window.location.href = "nopower.html";
					return;
				}
			} else {
				window.location.href = "apierror1.html";
				return;
			}
		},
		error : function(error) {
			window.location.href = "apierror2.html";
			return;
		}
	});
}

/**
 * 初始化白板
 */
function initWis() {
	var api = WISAPI.New('./interface.php');
	WIS.clientid_ = userid;
	WIS.Init({
		wisId : wisId,
		api : api,
		userid_ : userid,
		container : 'wis_context',
		width : 0,
		height : 0,
		success : function() {
			WIS.Color("#FF8C00");
			WIS.AllowDraw({
				ballow : true
			});

			if (WIS.GetCurrentDoc() == "" || WIS.GetCurrentDoc() == null) {
				alert(lang_msg['selppt'][lang]);
			}
		},
		failure : function(err) {
			console.log("init fail:  " + JSON.stringify(err));
			alert(lang_msg['loadpptFail'][lang]);
		},
		updateUser : function(total, data_) {
			$(".rightLabel #onlineNum").html(total);
			online_count = total;
			if (data_.state == 0) {
				handleStuout(data_.clientId);
			}
		},
		onConnect : function() {

		},
		onReconnect : function() {

		},
		onConnectClose : function() {

		},
		onDocLoad : function(info) {
			console.log("docObject:" + JSON.stringify(info));
			docObject = info;
			if (!!docObject) {
				$("#docList div[docId=" + docObject["id"] + "]").addClass(
						"selectDoc");
				$("#docList div[docId=" + docObject["id"] + "]").siblings()
						.removeClass("selectDoc");
			}
		},
		onPageChange : function(page, total) {
			pageNum = total;
			$("#pageList").html("");
			for (var i = 1; i <= total; i++) {
				var option = $("<option>").val(i).text(i);
				$("#pageList").append(option);
			}
			$("#pageList").val(page);
		}
	});
}

function initTool() {
	$(".colorList .toolItem").live("click", function() {
		WIS.Color($(this).attr("data-color"));
	});
	$(".lineList .toolItem").live("click", function() {
		WIS.LineWidth($(this).attr("data-line"));
	});
	$(".toolList .toolItem").live("click", function() {
		if ($(this).attr("id") == "lockTool") {
			drawLocked = !drawLocked;
			WIS.AllowDraw({
				ballow : !drawLocked
			});
		}else if($(this).attr("id") == "largeTool"){
			var cur_width = $("#wis_context").width();
			var des_width = cur_width + 50;
			var screenwidth = window.screen.width;
			var limitwidth = screenwidth -76 - 10 - 280;
			if(des_width > limitwidth) return;
			WIS.Resize(des_width,0);
		}else if($(this).attr("id") == "smallTool"){
			var cur_width = $("#wis_context").width();
			var des_width = cur_width - 50;
			if(des_width < 300) return;
			WIS.Resize(des_width,0);
		}else {
			WIS.SetDrawType($(this).attr("data-type") + "");
		}
	});
	
	$("#pageList").live("change",function(val) {
		WIS.ToPage($("#pageList").val());
	});
}

/** **************DMS相关**************** */
function AddMessage(name, msg, style) {
	var faceMsg = msg;
	for ( var item in faceMap) {
		faceMsg = faceMsg.replace(new RegExp("\\" + item, "g"),
				"<img src='images/faces/" + faceMap[item] + ".gif'/>");
	}
	var msgHtml = "<div><span class='" + style + "' >" + name + "：</span>"
			+ faceMsg + "</div>";
	$("#messageBox").html($("#messageBox").html() + msgHtml);
	$("#messageBox").scrollTop(
			document.getElementById("messageBox").scrollHeight);
}

function Publish() {
	var send = $("#msgSendTxt").val();
	if (send == "")
		return;
	send = jQuery('<div />').text(send).html();
	ROP.Publish('{  "name":"' + userName + '", "message": "' + send + '"}',
			topic_msg);
	$("#msgSendTxt").val("");
}

function initDms() {
	ROP.On("enter_suc", function() {
		AddMessage(lang_text['sysmsg'][lang], lang_msg['connSucc'][lang], "sysSpan");
		refreshUser();
	});
	ROP.On("reconnect", function() {
		AddMessage(lang_text['sysmsg'][lang], lang_msg['reconnect'][lang], "sysSpan");
	});
	ROP.On("offline", function(err) {
		AddMessage(lang_text['sysmsg'][lang], lang_msg['offline'][lang], "sysSpan");
		window.location.href = "doulogin.html";
		return;
	});
	ROP.On("enter_fail", function(err) {
		AddMessage(lang_text['sysmsg'][lang], lang_msg['connFail'][lang], "sysSpan");
	});
	ROP.On("losed", function() {
		AddMessage(lang_text['sysmsg'][lang], lang_msg['offline'][lang], "sysSpan");
	});
	ROP.On("publish_data", function(data, topic) {
		var d = eval('(' + data + ')');
		if (topic == topic_msg) {
			var msg = d["message"];
			if (msg != null) {
				AddMessage((!!d["name"]) ? d["name"] : lang_text['anonymous'][lang], msg);
			}
		}
		if (topic == topic_stu_to_teacher) {
			handleCtrlMsg(d);
		}

	});
	ROP.Enter(dmsPubKey, dmsSubKey,classid+"_"+userid);
	ROP.Subscribe(topic_msg);
	ROP.Subscribe(topic_stu_to_teacher);
	document.onkeydown = function(e) {
		if (e == null || e.keyCode == null || e.ctrlKey == null)
			return;
		if (e.keyCode == 13 && e.ctrlKey) {
			document.getElementById("msgSendTxt").value += "\n";
		} else if (e.keyCode == 13) {
			e.preventDefault();
			Publish();
		}
	};
}

function refreshUser() {
	setTimeout(function() {
		$("#stuList").empty();
		$(".stuView_vadio").empty();
		ROP.Publish('{"oper":"refresh"}', topic_teacher_to_stu);
	}, 1000);
}

function handleCtrlMsg(ctrlMsg) {
	if (ctrlMsg["oper"] == "enter") {
		handleStuenter(ctrlMsg);
	}
}

function handleStuenter(ctrlMsg) {
	var itemHtml = "<div stuId='" + ctrlMsg["userid"] + "' clientid='"
			+ ctrlMsg["clientid"] + "'><span>" + ctrlMsg["name"]
			+ "</span></div>";
	$("#stuList").append(itemHtml);
	
	var vadioHtml = '<div stuId="'+ctrlMsg["userid"]+'" clientid="'+ctrlMsg["clientid"]+'" class="stuView">'
		          + '    <div class="displayBox">'
		          + '        <iframe allowtransparency="true" frameBorder="0" scrolling="no" width="278px" height="180px" src="stu_play.html?lssapp_id=' + lssapp_id + '&stream_stu=stream_'+ ctrlMsg["userid"] +'" ></iframe>'
		          + '    </div>'
		          + '    <div class="displayCtrlBar">'
		          + '        <a class="offMicBtn" onclick="muteme(this,\''+ctrlMsg["userid"]+'\')">'+lang_text['mute'][lang]+'</a>'
		          + '        <span>'+ctrlMsg["name"]+lang_text['video'][lang]+'</span>'
		          + '    </div>'
		          + '</div>';
	$(".stuView_vadio").append(vadioHtml);
}

function muteme(obj,mute_userid){
	var objname = $(obj).html();
	if(objname == lang_text['mute'][lang]){
		ROP.Publish('{"userid": "'+ mute_userid +'","oper":"mute"}', topic_teacher_to_stu);
		$(obj).html(lang_text['voice'][lang]);
	}else{
		ROP.Publish('{"userid": "'+ mute_userid +'","oper":"nomute"}', topic_teacher_to_stu);
		$(obj).html(lang_text['mute'][lang]);
	}
}

function muteall(){
	var objname = $("#mute_oper").html();
	if(objname == lang_text['muteall'][lang]){
		ROP.Publish('{"oper":"muteall"}', topic_teacher_to_stu);
		$("#mute_oper").html(lang_text['voiceall'][lang]);
		$(".stuView .displayCtrlBar a").each(function(index,ele){
			$(this).html(lang_text['voice'][lang]);
		});
	}else{
		ROP.Publish('{"oper":"nomuteall"}', topic_teacher_to_stu);
		$("#mute_oper").html(lang_text['muteall'][lang]);
		$(".stuView .displayCtrlBar a").each(function(index,ele){
			$(this).html(lang_text['mute'][lang]);
		});
	}
}

function handleStuout(clientid) {
	$("#stuList div").each(function(index, element) {
		var clientid_ = $(this).attr("clientid");
		if (clientid == clientid_) {
			$(this).remove();
			return;
		}
	});
	$(".stuView").each(function(index, element) {
		var clientid_ = $(this).attr("clientid");
		if (clientid == clientid_) {
			$(this).remove();
			return;
		}
	});
}

function canvasSupport() {
	return !!document.createElement('canvas').getContext;
}

function publishme() {
	if (play_status == 0) {
		lss.initConnect();
		var publishConf = {
			micID : selmic,
			camID : selcam,
			audioKBitrate : 44,
			audioSamplerate : 44100,
			videoFPS : 10,
			keyFrameInterval : 30,
			videoKBitrate : 256,
			videoQuality : 80,
			volume : 80,
			isUseCam : true,
			isUseMic : true,
			isMute : false
		};
		lss.startPublish(publishConf);
		play_status = 1;
		$("#myoper").html(lang_text['stopWebcast'][lang]);
		$("#myset").hide();
	} else {
		lss.closeConnect();
		play_status = 0;
		$("#myoper").html(lang_text['myoper'][lang]);
		$("#myset").show();
	}

}

//收起或展开
var stuview_status = 1;//展开
function colexpme(){
	if(stuview_status == 1){//收起操作
		$(".stuView_all .stuView_vadio").animate({height: 'toggle', opacity: 'toggle'}, "slow");
		$("#order_oper").hide();
		$("#mute_oper").hide();
		$(".stuView_all").animate({width:"80px"},500);
		$("#colexp_oper").html(lang_text['expand'][lang]);
		stuview_status = 0;
	}else{
		$(".stuView_all .stuView_vadio").animate({height: 'toggle', opacity: 'toggle'}, "slow");
		if(order_status == 1)
			$(".stuView_all").animate({width:"585px"},500);
		else
			$(".stuView_all").animate({width:"288px"},500);
		$("#order_oper").show();
		$("#mute_oper").show();
		$("#colexp_oper").html(lang_text['collapse'][lang]);
		stuview_status = 1;
	}
}
//横排竖排
var order_status = 0;//竖排
function orderme(){
	if(order_status == 1){//转为竖排
		$(".stuView_all").animate({width:"288px"},500);
		$("#order_oper").html(lang_text['horizontal'][lang]);
		order_status = 0;
	}else{
		$(".stuView_all").animate({width:"585px"},500);
		$("#order_oper").html(lang_text['vertical'][lang]);
		order_status = 1;
	}
}

function initLss() {
	
	var stream_tea_tmp = stream_tea.replace(/-/g,'_');
	genK({
		appid : lssapp_id,
		stream : stream_tea_tmp,
		success : function(data) {
			console.log(data);
			lss = new aodianLss({
				container : 'playerView',
				url : rtmp_publish_url + '/' + lssapp_id + '/' + stream_tea_tmp + '?k=' + data.k + '&t=' + data.t ,
				width : '278',
				height : '180',
				autoconnect : true
			});
		},
		failure : function(errStr) {
			alert(errStr.responseText);
		}
	});
	
	if (!canvasSupport()) {
		$(".switchBtn").hide();
	}

	$("#selme").click(function() {
		if ($(this).is(':checked')) {
			setCookie("noprompt", "1", 365);
		} else {
			setCookie("noprompt", "2", 365);
		}
	});
}

function stopBubble(e) {
    if ( e && e.stopPropagation ){
        e.stopPropagation();
    }else{
        window.event.cancelBubble = true;
    }
}

function stopDefault(e) {
    if (e && e.preventDefault){
        e.preventDefault();
    }else{
        window.event.returnValue = false;
    }
    return false;
}

function myset(){
	var micArray = lss.getMic();
	var camArray = lss.getCam();
	if(!micArray || !camArray){
		alert(lang_msg['noDevice'][lang]);
		return;
	}
	$("#selmic option").remove();
	$("#selcam option").remove();
	for(var i=0;i<5;i++){
		if(micArray[i]){
			if(i == selmic){
				$("#selmic").append("<option value="+i+" selected>"+micArray[i]+"</option>");
			}else{
				$("#selmic").append("<option value="+i+">"+micArray[i]+"</option>");
			} 
		}
		if(camArray[i]){
			if(i == selcam){
				$("#selcam").append("<option value="+i+" selected>"+camArray[i]+"</option>");
			}else{
				$("#selcam").append("<option value="+i+">"+camArray[i]+"</option>");
			}
		}
	}
	$('#mysetModal').reveal();
}

var player = "mp3player";

function loadMp3Player(mp3file){
	var playerInstance = jwplayer(player);
	playerInstance.setup({
		file: mp3file,
		height: 30,
		width: "100%",
		events: {
            onPlay: function () {
            	var file = jwplayer(player).getPlaylistItem(0).file;
            	var position = jwplayer(player).getPosition();
            	var duration = jwplayer(player).getDuration();
            	if(position == duration) position = 0;
            	ROP.Publish('{"oper":"mp3play","file":"'+file+'","position":'+position+'}',topic_teacher_to_stu);
            },
            onPause: function () { 
            	ROP.Publish('{"oper":"mp3pause"}',topic_teacher_to_stu);
            },
            onMute: function (mute) {
            	ROP.Publish('{"oper":"mp3mute","mute":'+mute.mute+'}',topic_teacher_to_stu);
            },
            onSeek: function(seek){
            	ROP.Publish('{"oper":"mp3seek","offset":'+seek.offset+'}',topic_teacher_to_stu);
            }
        }
	});
	
}


function loadLang(option) {
	$.ajax({
		type : "POST",
		timeout : 8000,
		url : "./remoteinvoke.php",
		dataType : "json",
		data : {
			method : 'get_lang'
		},
		success : function(data) {
			if (data.Flag == 100) {
				if (option.success)
					option.success(data);
			} else {
				if (option.failure)
					option.failure(data.FlagString);
			}
		},
		error : option.failure
	});
}

function initLang(err) {
	if (err != null) {
		alert(err);
	}
	if(lang){
		setLangtext();
		return;
	}
	loadLang({
		success : function(data) {
			console.log(data);
			if(data.lang) lang = data.lang;
			setLangtext();
		},
		failure : function(errStr) {
			alert(errStr.responseText);
		}
	});
}

function setLangtext(){
	document.title = lang_text['title'][lang]; 
	$("#title").html(lang_text['title'][lang]);
	$("#operguide").html(lang_text['operguide'][lang]);
	$("#fullscreen").html(lang_text['fullscreen'][lang]);
	$("#startcapture").html(lang_text['startcapture'][lang]);
	$("#online").html(lang_text['online'][lang]);
	$("#colorTool").html(lang_text['colorTool'][lang]);
	$("#lineTool").html(lang_text['lineTool'][lang]);
	$("#otherTool").html(lang_text['otherTool'][lang]);
	$("#myoper").html(lang_text['myoper'][lang]);
	$("#myset").html(lang_text['myset'][lang]);
	$("#msgTab").html(lang_text['msgTab'][lang]);
	$("#docTab").html(lang_text['docTab'][lang]);
	$("#stuTab").html(lang_text['stuTab'][lang]);
	$("#sendBtn").html(lang_text['sendBtn'][lang]);
	$("#pptOffice").html(lang_text['pptOffice'][lang]);
	$("#pptMp3").html(lang_text['pptMp3'][lang]);
	$("#stuRefresh").html(lang_text['stuRefresh'][lang]);
	$("#colexp_oper").html(lang_text['collapse'][lang]);
	$("#order_oper").html(lang_text['horizontal'][lang]);
	$("#mute_oper").html(lang_text['muteall'][lang]);
	$("#impNote").html(lang_text['impNote'][lang]);
	$("#note1").html(lang_text['note1'][lang]);
	$("#note2").html(lang_text['note2'][lang]);
	$("#note3").html(lang_text['note3'][lang]);
	$("#note4").html(lang_text['note4'][lang]);
	$("#note5").html(lang_text['note5'][lang]);
	$("#note6").html(lang_text['note6'][lang]);
	$("#setMic").html(lang_text['setMic'][lang]);
	$("#setCam").html(lang_text['setCam'][lang]);
	$("#setok").val(lang_text['setok'][lang]);

	if (userName == null || userName.length == 0)
		userName = lang_text['anonymous'][lang];
}

var scrolltimer1;

$(function() {
	
	initParam();
	initLang();
	u_c_t(classid, userid);
	var interv = self.setInterval(function() {
		u_c_t_c(classid, userid);
	}, 60000);
	
	$(window).scroll(function() { 
		if(scrolltimer1) clearInterval(scrolltimer1);
		var top = $(window).scrollTop();
		if(top<64) top = 64;
		scrolltimer1=setInterval(function(){  
			$(".toolsBar").animate({top: top + "px" },300); 
			$(".rightBox").animate({top: top + "px" },300);
			$(".stuView_all").animate({top: top + "px" },300);
       },1000);
	});
	
	$("#setok").live("click",function(){
		selmic = $("#selmic").val();
		selcam = $("#selcam").val();
		setCookie("selmic", selmic, 365);
		setCookie("selcam", selcam, 365);
		$("#mysetModal").trigger('reveal:close');
	});
	
	setTimeout(function(){
		$('*').each(function(index,elem){
			try{
				$(this).live("touchmove",function (e) {
					stopDefault(e);
					stopBubble(e);
				});
			}catch(err){}
		});
	},1500);
});